package com.le.tester.imooc.oldfairy.dbgen;

import com.github.javafaker.Faker;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.function.Supplier;

/**
 * createTime：2022/1/11 15:42
 * description：开启多个线程行行的插入数据
 */
public class RowGen {
    //设置成生成的数据为简体中文
    Faker faker = new Faker(Locale.CHINA);
    //使用了静态初始化
    static ArrayList<BookLoader.Sentence> sentences = null;

    //先使用了静态的初始化，再使用{}中的初始化
    {
        try {
            //还是去读取文件了
            sentences = new BookLoader().sentences();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public String genBatch(String table, String column, int batchSize, Supplier<String> supplier) {
        List<String> batch = new LinkedList<>();
        for (int i = 0; i < batchSize; i++) {
            batch.add('(' + supplier.get() + ')');
        }
        String joined = String.join(",", batch);
        return String.format("insert into %s (%s) values " + joined + ";", table, column);

    }

    public String genUserBatch(int bucketSize) {

        String column = "`name`, `uname`, `pwd`, `salt`, `tel`, `address`, `avatar`, `ip`";
        return this.genBatch("og_user", column, bucketSize, () -> {
            String name = faker.name().firstName() + faker.name().lastName();
            String uname = faker.name().username();
            long salt = faker.number().randomNumber(6, false);
            String pwd = faker.number().digits(6);
            pwd = Hashing.sha256().hashString(pwd + salt, Charsets.UTF_8).toString();
            String tel = faker.phoneNumber().phoneNumber();
            String address = faker.address().fullAddress();
            String avatar = faker.avatar().image();
            String ip = faker.internet().ipV4Address();
            int[] ipvals = new int[4];
            String[] parts = ip.split("\\.");
            long ipInt = 0;
            for (int k = 0; k < 4; k++) {
                ipInt += ipvals[k] << (24 - (8 * k));
            }


            return String.format("'%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'",
                    name,
                    uname,
                    pwd,
                    salt,
                    tel,
                    address,
                    avatar,
                    ipInt
            );
        });
    }


    public String getBatchPost(int bucketSize, int userStart, int userEnd) {

        String column = "name,user_id,title,info,approve, dislike,state";
        return this.genBatch("og_post", column, bucketSize, () -> {
            String name = faker.name().fullName();
            int userId = (int) (Math.random() * (userEnd - userStart) + userStart);
            String title = faker.medical().medicineName();
            String info = sentences.get((int) (Math.random() * sentences.size())).text;
            long approve = Math.round(Math.random() * 10000);
            long dislike = Math.round(Math.random() * 10000);
            long state = Math.round(Math.random() * 4);

            SimpleDateFormat format = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
            title = title.replace("\'", "\\\'");
            if (title.length() > 12) {
                title = title.substring(0, 12);
            }
            return String.format("'%s', %s, '%s','%s',%s,%s,%s",
                    name,
                    userId,
                    title,
                    info,
                    approve,
                    dislike,
                    state
            );
        });
    }
}
